/**
 * Project Name:mauto-web
 * File Name:AreaService.java
 * Package Name:com.inftech.mauto.sys.service
 * Date:2016年10月7日下午9:14:13
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.core.service;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.inftech.mauto.common.base.BusinessException;
import com.inftech.mauto.common.constant.BusinessConstant;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.common.utils.CommonUtils;
import com.inftech.mauto.core.dao.ICarDao;
import com.inftech.mauto.core.dao.IFollowDao;
import com.inftech.mauto.core.dao.IOrderActionDao;
import com.inftech.mauto.core.dao.IOrderDao;
import com.inftech.mauto.core.dao.IOrderGoodsDao;
import com.inftech.mauto.core.entity.Car;
import com.inftech.mauto.core.entity.Follow;
import com.inftech.mauto.core.entity.Order;
import com.inftech.mauto.core.entity.OrderAction;
import com.inftech.mauto.core.entity.OrderGoods;
import com.inftech.mauto.sys.dao.IDictDao;
import com.inftech.mauto.sys.dao.IFileDao;
import com.inftech.mauto.sys.dao.IGoodsDao;
import com.inftech.mauto.sys.entity.File;
import com.inftech.mauto.sys.entity.Goods;
import com.inftech.mauto.sys.service.IdentifierService;
import com.mingsoft.base.biz.impl.BaseBizImpl;
import com.mingsoft.base.dao.IBaseDao;
import com.mingsoft.basic.entity.ManagerSessionEntity;
import com.mingsoft.weixin.dao.IWeixinDao;
import com.mingsoft.weixin.dao.IWeixinPeopleDao;
import com.mingsoft.weixin.entity.WeixinEntity;
import com.mingsoft.weixin.entity.WeixinPeopleEntity;
import com.mingsoft.weixin.util.MessageTemplateUtils;
import com.mingsoft.weixin.util.UploadDownUtils;

/**
 * 
 * ClassName: OrderService <br/>
 * Function: 订单service. <br/>
 * date: 2016年11月6日 下午10:24:00 <br/>
 *
 * @author puyf
 * @version
 * @since JDK 1.7
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Service("orderService")
public class OrderService extends BaseBizImpl {

	/**
	 * 订单持久化层注入
	 */
	@Autowired
	private IOrderDao orderDao;

	/**
	 * 订单商品持久化层注入
	 */
	@Autowired
	private IOrderGoodsDao orderGoodsDao;

	/**
	 * 商品持久化层注入
	 */
	@Autowired
	private IGoodsDao goodsDao;

	/**
	 * 回访持久化层注入
	 */
	@Autowired
	private IFollowDao followDao;

	/**
	 * 订单操作记录持久化层注入
	 */
	@Autowired
	private IOrderActionDao orderActionDao;

	/**
	 * 订单操作记录持久化层注入
	 */
	@Autowired
	private IdentifierService identifierService;

	/**
	 * 注入微信持久化层
	 */
	@Autowired
	private IWeixinDao weixinDao;

	/**
	 * 注入微信用户持久化层
	 */
	@Autowired
	private IWeixinPeopleDao weixinPeopleDao;

	/**
	 * 数据字典持久化层注入
	 */
	@Autowired
	private IDictDao dictDao;

	/**
	 * 文件持久化层注入
	 */
	@Autowired
	private IFileDao fileDao;

	/**
	 * 车辆持久化层注入
	 */
	@Autowired
	private ICarDao carDao;

	/**
	 * 文件服务器地址
	 */
	@Value("${fileUrl}")
	private String fileUrl;

	/**
	 * 文件路径
	 */
	@Value("${filePath}")
	private String filePath;

	/**
	 * 前台订单详情url（车主）
	 */
	@Value("${orderDetailUrlC}")
	private String orderDetailUrlC;

	/**
	 * 前台订单详情url（服务单位）
	 */
	@Value("${orderDetailUrlS}")
	private String orderDetailUrlS;

	/**
	 * 状态关系map
	 */
	private static Map<String, Integer> statusMap = new HashMap<String, Integer>();

	static {
		// 待审核
		statusMap.put(BusinessConstant.OSSTR_DSH, BusinessConstant.OSINT_DSH);
		// 待确认
		statusMap.put(BusinessConstant.OSSTR_DQR, BusinessConstant.OSINT_DQR);
		// 待维修
		statusMap.put(BusinessConstant.OSSTR_DWX, BusinessConstant.OSINT_DWX);
		// 待评价
		statusMap.put(BusinessConstant.OSSTR_DPJ, BusinessConstant.OSINT_DPJ);
		// 已完成
		statusMap.put(BusinessConstant.OSSTR_YWC, BusinessConstant.OSINT_YWC);
		// 已关闭
		statusMap.put(BusinessConstant.OSSTR_YGB1, BusinessConstant.OSINT_YGB);
		statusMap.put(BusinessConstant.OSSTR_YGB2, BusinessConstant.OSINT_YGB);
		statusMap.put(BusinessConstant.OSSTR_YGB3, BusinessConstant.OSINT_YGB);
	}

	@Override
	protected IBaseDao getDao() {
		return orderDao;
	}

	/**
	 * 
	 * queryOrderListFront:微信查询订单列表. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @param people
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public List<Map<String, Object>> queryOrderListFront(Map<String, Object> paramMap, WeixinPeopleEntity people)
			throws Exception {
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_C)) {
			// 车主角色
			paramMap.put("peopleId", people.getPeopleId());
		} else if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			// 服务单位角色
			paramMap.put("enterpriseId", people.getPeopleEnterpriseId());
		}

		// 状态转换，前台提交状态：0：全部；20：待处理；3：待维修；4：待评价
		int osInt = (int) paramMap.get("orderStatus");
		Set<Integer> osIntSet = new HashSet<Integer>();
		osIntSet.add(osInt);
		Set<String> osStringSet = convertOrderStatus(osIntSet, true);
		paramMap.put("orderItemType", BusinessConstant.ORDER_ITEM_TYPE_BP);

		// 特殊处理项
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			// 服务单位角色
			// 处理掉未审核就取消掉的订单
			osStringSet.remove(BusinessConstant.OSSTR_YGB1);
			if (osInt == BusinessConstant.OSINT_ALL) {
				// 获取所有订单列表接口特殊处理，取满足条件的3个月内的订单
				paramMap.put("orderCreateTimeBegin", CommonUtils.getDate(-90));
			}
		}
		paramMap.put("orderStatus", osStringSet);
		// 获取订单列表
		List<Order> orderList = orderDao.queryOrderList(paramMap);
		// 返回列表
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (orderList != null && orderList.size() != 0) {
			for (Order order : orderList) {
				Map<String, Object> orderM = new HashMap<String, Object>();
				// 订单id
				orderM.put("id", order.getId());
				// 订单编号
				orderM.put("orderCode", order.getOrderCode());
				// 服务单位名称
				orderM.put("enterpriseName", order.getEnterpriseName());
				// 预估报价
				orderM.put("orderTotalAmount", order.getOrderTotalAmount());
				// 订单状态
				String osStr = getOsStr(order);
				osInt = convertOrderStatus(osStr, true);
				orderM.put("orderStatus", osInt);
				// 车牌号
				orderM.put("carPlateNumber", order.getCarPlateNumber());
				// 联系人
				orderM.put("orderContact", order.getOrderContact());
				// 联系电话
				orderM.put("orderContactPhone", order.getOrderContactPhone());
				// 应付金额
				orderM.put("orderReceiveAmount", order.getOrderReceiveAmount());
				// 预约时间
				if (!CommonUtils.isBlank(order.getOrderAppointTime())) {
					orderM.put("orderAppointTime", CommonUtils.formatDate3(order.getOrderAppointTime()));
				}
				// 是否出险
				orderM.put("isInsurance", order.getIsInsurance());
				resultList.add(orderM);
			}
		}
		return resultList;
	}
	
	public Map<String,Object> queryAllOrderList(Map<String, Object> paramMap, WeixinPeopleEntity people)
			throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_C)) {
			// 车主角色
			paramMap.put("peopleId", people.getPeopleId());
		} else if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			// 服务单位角色
			paramMap.put("enterpriseId", people.getPeopleEnterpriseId());
		}

		// 状态转换，前台提交状态：0：全部；20：待处理；3：待维修；4：待评价
		int osInt = Integer.parseInt(paramMap.get("orderStatus").toString());
		Set<Integer> osIntSet = new HashSet<Integer>();
		osIntSet.add(osInt);
		Set<String> osStringSet = convertOrderStatus(osIntSet, true);
		paramMap.put("orderItemType", BusinessConstant.ORDER_ITEM_TYPE_BP);

		// 特殊处理项
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			// 服务单位角色
			// 处理掉未审核就取消掉的订单
			osStringSet.remove(BusinessConstant.OSSTR_YGB1);
			if (osInt == BusinessConstant.OSINT_ALL) {
				// 获取所有订单列表接口特殊处理，取满足条件的3个月内的订单
				paramMap.put("orderCreateTimeBegin", CommonUtils.getDate(-90));
			}
		}
		paramMap.put("orderStatus", osStringSet);
		// 获取订单列表
		List<Order> orderList = orderDao.queryAllOrderList(paramMap);
		
		int orderCount = orderDao.queryAllOrderCount(paramMap);
		// 返回列表
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (orderList != null && orderList.size() != 0) {
			for (Order order : orderList) {
				Map<String, Object> orderM = new HashMap<String, Object>();
				// 订单id
				orderM.put("id", order.getId());
				// 订单编号
				orderM.put("orderCode", order.getOrderCode());
				// 服务单位名称
				orderM.put("enterpriseName", order.getEnterpriseName());
				// 预估报价
				orderM.put("orderTotalAmount", order.getOrderTotalAmount());
				// 订单状态
				String orderType = order.getOrderType();
				if("BP".equals(orderType)) {
					String osStr = getOsStr(order);
					osInt = convertOrderStatus(osStr, true);
					orderM.put("orderStatus", osInt);
				} else {
					orderM.put("orderStatus", order.getOrderStatus()+order.getOrderCommentStatus());
				}
				// 车牌号
				orderM.put("carPlateNumber", order.getCarPlateNumber());
				// 联系人
				orderM.put("orderContact", order.getOrderContact());
				// 联系电话
				orderM.put("orderContactPhone", order.getOrderContactPhone());
				// 应付金额
				orderM.put("orderReceiveAmount", order.getOrderReceiveAmount());
				// 预约时间
				if (!CommonUtils.isBlank(order.getOrderAppointTime())) {
					orderM.put("orderAppointTime", CommonUtils.formatDate3(order.getOrderAppointTime()));
				}
				// 是否出险
				orderM.put("isInsurance", order.getIsInsurance());
				orderM.put("orderType", orderType);
				orderM.put("carXh", order.getCarXh());
				orderM.put("carDate", order.getCarDate());
				orderM.put("carXslc", order.getCarXslc());
				orderM.put("orderXmNum", order.getOrderXmNum());
				orderM.put("orderSum", order.getOrderSum());
				
				resultList.add(orderM);
			}
		}
		map.put("list", resultList);
		map.put("count", orderCount);
		return map;
	}

	/**
	 * 
	 * queryOrderList:后台查询订单列表. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public List<Order> queryOrderList(Map<String, Object> paramMap) throws Exception {
		int osInt = paramMap.get("orderStatus") == null ? 0 : Integer.parseInt((String) paramMap.get("orderStatus"));
		Set<Integer> osIntSet = new HashSet<Integer>();
		osIntSet.add(osInt);
		Set<String> osStringSet = convertOrderStatus(osIntSet, false);
		paramMap.put("orderItemType", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("orderStatus", osStringSet);
		// 获取订单列表
		List<Order> orderList = orderDao.queryOrderList(paramMap);
		if (orderList != null) {
			for (Order order : orderList) {
				// 订单状态
				String osStr = getOsStr(order);
				osInt = convertOrderStatus(osStr, false);
				order.setOrderStatus((byte) osInt);
			}
		}
		return orderList;

	}

	/**
	 * 
	 * queryOrderFront:查询订单详细. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @param people
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Map<String, Object> queryOrderFront(Map<String, Object> paramMap, WeixinPeopleEntity people)
			throws Exception {
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_C)) {
			// 车主角色
			paramMap.put("people_id", people.getPeopleId());
		} else if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			// 服务单位角色
			paramMap.put("enterprise_id", people.getPeopleEnterpriseId());
		}
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order order = orderDao.getEntity(paramMap);
		/*
		 * String orderGoodsStr = ""; if (order != null) { // 通过订单id获取订单商品列表
		 * paramMap.clear(); paramMap.put("orderId", order.getId());
		 * List<OrderGoods> orderGoodsList =
		 * orderGoodsDao.queryOrderGoodsList(paramMap); if (orderGoodsList !=
		 * null && orderGoodsList.size() != 0) { for (OrderGoods orderGoods :
		 * orderGoodsList) { // TODO 处理钣喷项目 } } }
		 */
		// 返回对象
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单id
		resultMap.put("id", order.getId());
		// 订单状态
		String osStr = getOsStr(order);
		int osInt = convertOrderStatus(osStr, true);
		resultMap.put("orderStatus", osInt);
		// 车牌号
		resultMap.put("carPlateNumber", order.getCarPlateNumber());
		// 品牌
		resultMap.put("carBrand", order.getCarBrand());
		// 型号
		resultMap.put("carModel", order.getCarModel());
		// 购车价格
		resultMap.put("carBuyPrice", order.getCarBuyPrice());
		// 购买日期
		resultMap.put("carBuyDate", order.getCarBuyDate());
		// 联系人
		resultMap.put("orderContact", order.getOrderContact());
		// 联系人电话
		resultMap.put("orderContactPhone", order.getOrderContactPhone());
		// 企业名称
		resultMap.put("enterpriseName", order.getEnterpriseName());
		// 企业地址
		resultMap.put("enterpriseAddress", order.getEnterpriseAddress());
		// 企业联系电话
		resultMap.put("enterpriseTel", order.getEnterpriseTel());
		// 企业gps
		resultMap.put("enterpriseGps", order.getEnterpriseGps());
		// 服务项目
		resultMap.put("orderGoods", order.getOrderGoods());
		// 订单总额
		resultMap.put("orderTotalAmount", order.getOrderTotalAmount());
		// 实收金额
		resultMap.put("orderReceiveAmount", order.getOrderReceiveAmount());
		// 是否出险
		resultMap.put("isInsurance", order.getIsInsurance());
		// 订单编号
		resultMap.put("orderCode", order.getOrderCode());
		// 生成时间
		if (!CommonUtils.isBlank(order.getOrderCreateTime())) {
			resultMap.put("orderCreateTime", CommonUtils.formatDate3(order.getOrderCreateTime()));
		}
		// 审核时间
		if (!CommonUtils.isBlank(order.getOrderCheckTime())) {
			resultMap.put("orderCheckTime", CommonUtils.formatDate3(order.getOrderCheckTime()));
		}
		// 确认时间
		if (!CommonUtils.isBlank(order.getOrderConfirmTime())) {
			resultMap.put("orderConfirmTime", CommonUtils.formatDate3(order.getOrderConfirmTime()));
		}
		// 预约时间
		if (!CommonUtils.isBlank(order.getOrderAppointTime())) {
			resultMap.put("orderAppointTime", CommonUtils.formatDate3(order.getOrderAppointTime()));
		}
		// 取消时间
		if (!CommonUtils.isBlank(order.getOrderCancelTime())) {
			resultMap.put("orderCancelTime", CommonUtils.formatDate3(order.getOrderCancelTime()));
		}
		// 竣工时间
		if (!CommonUtils.isBlank(order.getOrderSignTime())) {
			resultMap.put("orderSignTime", CommonUtils.formatDate3(order.getOrderSignTime()));
		}
		// 评价时间
		if (!CommonUtils.isBlank(order.getOrderCommentTime())) {
			resultMap.put("orderCommentTime", CommonUtils.formatDate3(order.getOrderCommentTime()));
		}
		// 钣喷图片
		if (!CommonUtils.isBlank(order.getOrderImagesStr())) {
			String[] orderImageArray = order.getOrderImagesStr().split(",");
			StringBuilder orderImagesSB = new StringBuilder();
			for (String orderImage : orderImageArray) {
				orderImagesSB.append(fileUrl + orderImage);
				orderImagesSB.append(",");
			}
			resultMap.put("orderImages", orderImagesSB.substring(0, orderImagesSB.length() - 1));
		}
		return resultMap;
	}

	/**
	 * 
	 * queryOrder:查询订单详细. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Order queryOrder(Map<String, Object> paramMap) throws Exception {
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order order = orderDao.getEntity(paramMap);
		/*
		 * String orderGoodsStr = ""; if (order != null) { // 通过订单id获取订单商品列表
		 * paramMap.clear(); paramMap.put("orderId", order.getId());
		 * List<OrderGoods> orderGoodsList =
		 * orderGoodsDao.queryOrderGoodsList(paramMap); if (orderGoodsList !=
		 * null && orderGoodsList.size() != 0) { for (OrderGoods orderGoods :
		 * orderGoodsList) { // TODO 处理钣喷项目 } } }
		 */
		// 订单状态
		String osStr = getOsStr(order);
		int osInt = convertOrderStatus(osStr, false);
		order.setOrderStatus((byte) osInt);
		// 钣喷图片
		if (!CommonUtils.isBlank(order.getOrderImagesStr())) {
			String[] orderImageArray = order.getOrderImagesStr().split(",");
			for (int i = 0; i < orderImageArray.length; i++) {
				orderImageArray[i] = fileUrl + orderImageArray[i];
			}
			order.setOrderImages(orderImageArray);
		}
		return order;
	}

	/**
	 * 
	 * queryOrderCount:获取订单数量. <br/>
	 *
	 * @author puyf
	 * @param people
	 * @return
	 * @since JDK 1.7
	 */
	public Map<String, Object> queryOrderCount(WeixinPeopleEntity people) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("enterpriseId", people.getPeopleEnterpriseId());
		// 查询待确认的订单数量
		paramMap.put("orderStatus", Arrays.asList(BusinessConstant.OSSTR_DQR));
		int DQRCount = orderDao.queryOrderCount(paramMap);
		// 查询待维修的订单数量
		paramMap.put("orderStatus", Arrays.asList(BusinessConstant.OSSTR_DWX));
		int DWXCount = orderDao.queryOrderCount(paramMap);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("DQRCount", DQRCount);
		resultMap.put("DWXCount", DWXCount);
		return resultMap;
	}

	/**
	 * 
	 * saveOrder:新增订单. <br/>
	 *
	 * @author puyf
	 * @param order
	 * @param people
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void saveOrder(Order order, WeixinPeopleEntity people) throws Exception {
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
			LOG.error("新增订单失败，角色不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
		}
		String[] goodsCodeArray = order.getGoodsCodes().split(",");
		String carBuyPrice = order.getCarBuyPrice();
		// 商品准确性判断
		for (String goodsCode : goodsCodeArray) {
			if (!goodsCode.startsWith(carBuyPrice)) {
				LOG.error("新增订单失败，所选商品不正确");
				throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_942);
			}
		}
		// 获取商品列表
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("goodsCodes", goodsCodeArray);
		List<Goods> goodsList = goodsDao.queryGoodsList(paramMap);
		// 判断商品总价
		BigDecimal orderTotalAmountDB = new BigDecimal(0.00);
		for (Goods goods : goodsList) {
			orderTotalAmountDB = orderTotalAmountDB.add(goods.getGoodsPrice());
		}
		if (orderTotalAmountDB.compareTo(order.getOrderTotalAmount()) != 0) {
			LOG.error("新增订单失败，订单金额不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_943);
		}

		// 插入订单
		final String orderCode = identifierService.readIdentifierBySeparator(BusinessConstant.ORDER_SEPARATOR_BP);
		final int peopleId = people.getPeopleId();
		final String[] orderImages = order.getOrderImages();
		final Date now = CommonUtils.getNowD();
		order.setOrderCode(orderCode);
		order.setPeopleId(peopleId);
		order.setOrderItemType(BusinessConstant.ORDER_ITEM_TYPE_BP);
		order.setOrderCreateTime(now);
		order.setOrderStatus(BusinessConstant.OS_WWC);
		order.setOrderCheckStatus(BusinessConstant.OCS_WSH);
		order.setOrderConfirmStatus(BusinessConstant.OCS_WQR);
		order.setOrderPayStatus(BusinessConstant.OPS_WZF);
		order.setOrderSignStatus(BusinessConstant.OSS_WQS);
		order.setOrderFollowStatus(BusinessConstant.OFS_WHF);
		order.setOrderCommentStatus(BusinessConstant.OCS_WPJ);
		order.setCreateBy(peopleId);
		order.setCreateDate(now);
		order.setUpdateDate(now);
		order.setDelFlag(0);
		orderDao.saveEntity(order);
		final String orderId = order.getId();
		// 图片处理
		if (order.getOrderImages() != null && order.getOrderImages().length != 0) {

			Thread downloadThread = new Thread(new Runnable() {

				@Override
				public void run() {
					List<String> insertFileList = new ArrayList<String>();
					// 订单图片文件夹
					String middlePath = "banpen" + "/" + CommonUtils.getThisYear() + "/" + CommonUtils.getThisMonth()
							+ "/" + orderCode;
					String imagePath = filePath + middlePath;

					WeixinEntity weixin = weixinDao.getEntity(null, null, null);
					UploadDownUtils uploadDownUtils = new UploadDownUtils(weixin.getWeixinAppID(),
							weixin.getWeixinAppSecret());
					for (String orderImage : orderImages) {
						// 下载图片
						String fileName = uploadDownUtils.downMedia(orderImage, imagePath);
						insertFileList.add(middlePath + "/" + fileName);
					}
					// 插入文件表
					for (String filePath : insertFileList) {
						File file = new File();
						file.setObjectId(Integer.valueOf(orderId));
						file.setObjectType(BusinessConstant.FILE_TYPE_BP_IMG);
						file.setFilePath(filePath);
						file.setCreateBy(peopleId);
						file.setCreateDate(now);
						file.setUpdateDate(now);
						file.setDelFlag(0);
						fileDao.saveEntity(file);
					}

				}
			});
			downloadThread.start();

		}

		// 插入订单配件
		for (Goods goods : goodsList) {
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setOrderId(Integer.parseInt(orderId));
			orderGoods.setGoodsId(Integer.parseInt(goods.getId()));
			orderGoods.setOgPrice(goods.getGoodsPrice());
			orderGoods.setOgNum((short) 1);
			orderGoods.setOgTotalAmount(goods.getGoodsPrice().multiply(new BigDecimal(1)));
			orderGoods.setCreateBy(peopleId);
			orderGoods.setCreateDate(now);
			orderGoods.setUpdateDate(now);
			orderGoods.setDelFlag(0);
			orderGoodsDao.saveEntity(orderGoods);
		}
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_CREATE, peopleId, now, Integer.parseInt(orderId),
				BusinessConstant.OS_WWC, BusinessConstant.OCS_WSH, BusinessConstant.OCS_WQR, BusinessConstant.OPS_WZF,
				BusinessConstant.OSS_WQS, BusinessConstant.OFS_WHF, BusinessConstant.OCS_WPJ);

		// 绑定我的车辆
		// 通过用户id查询用户车辆信息
		paramMap.clear();
		paramMap.put("people_id", peopleId);
		paramMap.put("del_flag", 0);
		Car carDB = carDao.getEntity(paramMap);
		if (carDB == null) {
			// 用户未绑定车辆，进行车辆绑定
			Car car = new Car();
			car.setPeopleId(peopleId);
			car.setCarPlateNumber(order.getCarPlateNumber());
			car.setCarBrand(order.getCarBrand());
			car.setCarModel(order.getCarModel());
			car.setCarBuyPrice(carBuyPrice);
			car.setCarBuyDate(order.getCarBuyDate());
			car.setCreateBy(peopleId);
			car.setCreateDate(now);
			car.setUpdateDate(now);
			car.setCarAddTime(now);
			car.setDelFlag(0);
			carDao.saveEntity(car);
		}
	}

	/**
	 * 
	 * modifyOrderAppontmentTime:修改订单预约时间. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @param people
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderAppontmentTime(Map<String, Object> map, WeixinPeopleEntity people) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("order_code", map.get("orderCode"));
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (!peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)
				|| orderDB.getEnterpriseId() != people.getPeopleEnterpriseId()) {
			LOG.error("修改订单预约时间失败，无数据操作权限");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
		}
		// 状态判断(合法状态：待维修)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DWX)) {
			LOG.error("修改订单预约时间失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode((String) map.get("orderCode"));
		order.setOrderAppointTime(CommonUtils.parseDate3((String) map.get("orderAppointTime")));
		order.setUpdateDate(now);
		order.setUpdateBy(people.getPeopleId());
		orderDao.updateEntity(order);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_MODIFY, people.getPeopleId(), now,
				Integer.parseInt(orderDB.getId()), orderDB.getOrderStatus(), orderDB.getOrderCheckStatus(),
				orderDB.getOrderConfirmStatus(), orderDB.getOrderPayStatus(), orderDB.getOrderSignStatus(),
				orderDB.getOrderFollowStatus(), orderDB.getOrderCommentStatus());
		// 发送订单确认消息模版
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());

		// 车主端
		// 通过用户id获取车主openId
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("peopleId", orderDB.getPeopleId());
		WeixinPeopleEntity weixinPeopleC = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
		messageTemplateUtils.sendToUser(weixinPeopleC.getWeixinPeopleOpenId(),
				"3RYbtD14h9VmGX1TwaVfYxPZsYN2o4ta52wbSBN-ji8", orderDetailUrlC + orderDB.getOrderCode(), "#000000",
				"尊敬的客户，您的服务预约时间已经变更！", "#000000", "请您于预约当天提前15分钟到店。祝您生活愉快，谢谢！", "#000000", orderDB.getOrderGoods(),
				CommonUtils.formatDate3(order.getOrderAppointTime()), orderDB.getEnterpriseName(),
				orderDB.getEnterpriseTel());
		LOG.info("向openId" + weixinPeopleC.getWeixinPeopleOpenId() + "推送预约时间变更消息成功");
	}

	/**
	 * 
	 * modifyOrderCancel:取消订单. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @param user
	 * @param isFront
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderCancel(Map<String, Object> map, Object user, boolean isFront) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("order_code", map.get("orderCode"));
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 操作来源（0：客服；1：车主；2：服务单位）
		int from = -1;
		int peopleId = 0;
		if (isFront) {
			WeixinPeopleEntity people = (WeixinPeopleEntity) user;
			peopleId = people.getPeopleId();
		} else {
			// 后台请求，用户id用负值描述
			from = 0;
			ManagerSessionEntity managerSession = (ManagerSessionEntity) user;
			peopleId = 0 - managerSession.getManagerId();
		}
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		if (isFront) {
			WeixinPeopleEntity people = (WeixinPeopleEntity) user;
			// 角色判断
			Byte peopleRole = people.getPeopleRole();
			if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_C)) {
				// 车主角色
				from = 1;
				if (orderDB.getPeopleId() != people.getPeopleId()) {
					LOG.error("车主取消订单失败，无数据操作权限");
					throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
				}
			} else if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
				// 服务单位角色
				from = 2;
				if (orderDB.getEnterpriseId() != people.getPeopleEnterpriseId()) {
					LOG.error("服务单位取消订单失败，无数据操作权限");
					throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
				}
			}
		}
		// 状态判断(合法状态：待审核、待确认、待维修)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DSH) && !osStr.equals(BusinessConstant.OSSTR_DQR)
				&& !osStr.equals(BusinessConstant.OSSTR_DWX)) {
			LOG.error("取消订单失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode((String) map.get("orderCode"));
		order.setOrderCancelReason((String) map.get("orderCancelReason"));
		if (!CommonUtils.isBlank(map.get("orderCancelRemark"))) {
			order.setOrderCancelRemark((String) map.get("orderCancelRemark"));
		}
		order.setOrderStatus(BusinessConstant.OS_YGB);
		order.setOrderCancelTime(now);
		order.setUpdateDate(now);
		order.setUpdateBy(peopleId);
		orderDao.updateEntity(order);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_CANCEL, peopleId, now, Integer.parseInt(orderDB.getId()),
				BusinessConstant.OS_YGB, orderDB.getOrderCheckStatus(), orderDB.getOrderConfirmStatus(),
				orderDB.getOrderPayStatus(), orderDB.getOrderSignStatus(), orderDB.getOrderFollowStatus(),
				orderDB.getOrderCommentStatus());
		// 发送订单取消消息模版
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());
		// String cancelReason =
		// dictDao.queryDict(order.getOrderCancelReason()).getDictValue();
		String cancelReason = "";
		if (from == 0) {
			cancelReason = "平台客服取消";
		} else if (from == 1) {
			cancelReason = "车主自行取消";
		} else if (from == 2) {
			cancelReason = "服务单位人员取消";
		}
		// 车主端
		// 通过用户id获取车主openId
		Map<String, Object> requestMap1 = new HashMap<String, Object>();
		requestMap1.put("peopleId", orderDB.getPeopleId());
		WeixinPeopleEntity weixinPeopleC = weixinPeopleDao.getWeixinPeopleEntity(requestMap1);
		messageTemplateUtils.sendToUser(weixinPeopleC.getWeixinPeopleOpenId(),
				"lSr1ltC6sIHz4Qgl4KnJ_S1qSBlgYfJy1_Crm2zSl14", orderDetailUrlC + orderDB.getOrderCode(), "#000000",
				"您好，您的订单已取消。", "#000000", "感谢您的关注和支持！", "#000000", orderDB.getOrderCode(), cancelReason);
		LOG.info("向openId" + weixinPeopleC.getWeixinPeopleOpenId() + "推送取消订单消息成功");

		if (osStr.equals(BusinessConstant.OSSTR_DWX)) {
			// 服务单位端
			// 通过服务单位id获取服务人员openId
			Map<String, Object> requestMap2 = new HashMap<String, Object>();
			requestMap2.put("enterpriseId", orderDB.getEnterpriseId());
			WeixinPeopleEntity weixinPeopleS = weixinPeopleDao.getWeixinPeopleEntity(requestMap2);
			messageTemplateUtils.sendToUser(weixinPeopleS.getWeixinPeopleOpenId(),
					"lSr1ltC6sIHz4Qgl4KnJ_S1qSBlgYfJy1_Crm2zSl14", orderDetailUrlS + orderDB.getOrderCode(), "#000000",
					"您好，车牌号 " + orderDB.getCarPlateNumber() + " 的订单已取消。", "#000000", "", "#000000",
					orderDB.getOrderCode(), cancelReason);
			LOG.info("向openId" + weixinPeopleS.getWeixinPeopleOpenId() + "推送取消订单消息成功");
		}
	}

	/**
	 * 
	 * modifyOrderCheck:审核订单. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderCheck(Map<String, Object> map) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String orderCode = (String) map.get("orderCode");
		int orderCheckManagerId = (int) map.get("managerId");
		paramMap.put("order_code", orderCode);
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		// 状态判断(合法状态：待审核)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DSH)) {
			LOG.error("审核订单失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode(orderCode);
		order.setOrderCheckManagerId(orderCheckManagerId);
		order.setOrderCheckTime(now);
		order.setOrderCheckStatus(BusinessConstant.OCS_YSH);
		order.setUpdateDate(now);
		order.setUpdateBy(0 - orderCheckManagerId);
		orderDao.updateEntity(order);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_CHECK, 0 - orderCheckManagerId, now,
				Integer.parseInt(orderDB.getId()), orderDB.getOrderStatus(), BusinessConstant.OCS_YSH,
				orderDB.getOrderConfirmStatus(), orderDB.getOrderPayStatus(), orderDB.getOrderSignStatus(),
				orderDB.getOrderFollowStatus(), orderDB.getOrderCommentStatus());
		// 发送新订单消息模版
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());
		// 通过服务单位id获取服务人员信息
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("enterpriseId", orderDB.getEnterpriseId());
		WeixinPeopleEntity weixinPeople = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
		String openId = weixinPeople.getWeixinPeopleOpenId();
		messageTemplateUtils.sendToUser(openId, "ZdCnLvesQydkhf9TCwb48Ui8P_2lpPKYFX1-9Za8OcY",
				orderDetailUrlS + orderDB.getOrderCode(), "#000000", "您好，您有新的客户订单。", "#000000", "请及时与车主联系。", "#000000",
				orderDB.getOrderContact(), orderDB.getOrderContactPhone(),
				orderDB.getCarBrand() + orderDB.getCarModel() + "（" + orderDB.getCarPlateNumber() + "）",
				orderDB.getOrderTotalAmount() + "（预估）", "-");
		LOG.info("向openId" + openId + "推送新订单消息成功");
	}

	/**
	 * 
	 * modifyOrderConfirm:确认订单. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @param people
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderConfirm(Map<String, Object> map, WeixinPeopleEntity people) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("order_code", map.get("orderCode"));
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (!peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)
				|| orderDB.getEnterpriseId() != people.getPeopleEnterpriseId()) {
			LOG.error("确认订单失败，无数据操作权限");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
		}
		// 状态判断(合法状态：待确认)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DQR)) {
			LOG.error("确认订单失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode((String) map.get("orderCode"));
		order.setOrderAppointTime(CommonUtils.parseDate3((String) map.get("orderAppointTime")));
		order.setOrderConfirmStatus(BusinessConstant.OCS_YQR);
		order.setOrderConfirmTime(now);
		order.setUpdateDate(now);
		order.setUpdateBy(people.getPeopleId());
		orderDao.updateEntity(order);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_CONFIRM, people.getPeopleId(), now,
				Integer.parseInt(orderDB.getId()), orderDB.getOrderStatus(), orderDB.getOrderCheckStatus(),
				BusinessConstant.OCS_YQR, orderDB.getOrderPayStatus(), orderDB.getOrderSignStatus(),
				orderDB.getOrderFollowStatus(), orderDB.getOrderCommentStatus());
		// 发送订单确认消息模版
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());

		// 车主端
		// 通过用户id获取车主openId
		Map<String, Object> requestMap1 = new HashMap<String, Object>();
		requestMap1.put("peopleId", orderDB.getPeopleId());
		WeixinPeopleEntity weixinPeopleC = weixinPeopleDao.getWeixinPeopleEntity(requestMap1);
		messageTemplateUtils.sendToUser(weixinPeopleC.getWeixinPeopleOpenId(),
				"HuBJWwgOZdgabHmzxNSQ1j1M6mqekk2EdBI9-6T0SEE", orderDetailUrlC + orderDB.getOrderCode(), "#000000",
				"您好，您已成功预约！", "#000000", "请您于预约当天提前15分钟到店。祝您生活愉快，谢谢！", "#000000", orderDB.getCarPlateNumber(),
				orderDB.getOrderGoods(), CommonUtils.formatDate3(order.getOrderAppointTime()));
		LOG.info("向openId" + weixinPeopleC.getWeixinPeopleOpenId() + "推送订单预约成功消息成功");

		// 服务单位端
		// 通过服务单位id获取服务人员openId
		Map<String, Object> requestMap2 = new HashMap<String, Object>();
		requestMap2.put("enterpriseId", orderDB.getEnterpriseId());
		WeixinPeopleEntity weixinPeopleS = weixinPeopleDao.getWeixinPeopleEntity(requestMap2);
		messageTemplateUtils.sendToUser(weixinPeopleS.getWeixinPeopleOpenId(),
				"HuBJWwgOZdgabHmzxNSQ1j1M6mqekk2EdBI9-6T0SEE", orderDetailUrlS + orderDB.getOrderCode(), "#000000",
				"您好，您有新的预约信息！", "#000000", "请尽早做好安排，并积极与车主确认进店时间。", "#000000", orderDB.getCarPlateNumber(),
				orderDB.getOrderGoods(), CommonUtils.formatDate3(order.getOrderAppointTime()));
		LOG.info("向openId" + weixinPeopleS.getWeixinPeopleOpenId() + "推送订单预约成功消息成功");
	}

	/**
	 * 
	 * modifyOrderSign:签收订单. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @param people
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderSign(Map<String, Object> map, WeixinPeopleEntity people) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("order_code", map.get("orderCode"));
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		// 角色判断
		Byte peopleRole = people.getPeopleRole();
		if (!peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)
				|| orderDB.getEnterpriseId() != people.getPeopleEnterpriseId()) {
			LOG.error("签收订单失败，无数据操作权限");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_403);
		}
		// 状态判断(合法状态：待维修)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DWX)) {
			LOG.error("签收订单失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode((String) map.get("orderCode"));
		// order.setOrderReceiveAmount(new BigDecimal((String)
		// map.get("receiveAmount")));
		// order.setOrderDiscountAmount(
		// orderDB.getOrderTotalAmount().subtract(new BigDecimal((String)
		// map.get("receiveAmount"))));
		order.setOrderSignStatus(BusinessConstant.OSS_YQS);
		order.setOrderSignTime(now);
		order.setUpdateDate(now);
		order.setUpdateBy(people.getPeopleId());
		orderDao.updateEntity(order);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_SIGN, people.getPeopleId(), now,
				Integer.parseInt(orderDB.getId()), orderDB.getOrderStatus(), orderDB.getOrderCheckStatus(),
				orderDB.getOrderConfirmStatus(), orderDB.getOrderPayStatus(), BusinessConstant.OSS_YQS,
				orderDB.getOrderFollowStatus(), orderDB.getOrderCommentStatus());
		// 发送订单取消消息模版
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());
		// 车主端
		// 通过用户id获取车主openId
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("peopleId", orderDB.getPeopleId());
		WeixinPeopleEntity weixinPeopleC = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
		messageTemplateUtils.sendToUser(weixinPeopleC.getWeixinPeopleOpenId(),
				"tuJeAEDbJCdBBs8IHD2ugm5BvtRF56U9C4BPZGPAT7Y", orderDetailUrlC + orderDB.getOrderCode(), "#000000",
				"您好，您的车辆已完成维修。", "#000000", "请您对本次服务进行评价。", "#000000", order.getOrderCode(), "待评价");
		LOG.info("向openId" + weixinPeopleC.getWeixinPeopleOpenId() + "推送订单状态变更消息成功");
	}

	/**
	 * 
	 * modifyOrderFollow:回访订单. <br/>
	 *
	 * @author puyf
	 * @param map
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyOrderFollow(Map<String, Object> map) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String orderCode = (String) map.get("orderCode");
		int managerId = (int) map.get("managerId");
		paramMap.put("order_code", orderCode);
		paramMap.put("order_item_type", BusinessConstant.ORDER_ITEM_TYPE_BP);
		paramMap.put("del_flag", 0);
		// 获取订单详情
		Order orderDB = orderDao.getEntity(paramMap);
		// 状态判断(合法状态：待维修、待评价、已完成)
		String osStr = getOsStr(orderDB);
		if (!osStr.equals(BusinessConstant.OSSTR_DWX) && !osStr.equals(BusinessConstant.OSSTR_DPJ)
				&& !osStr.equals(BusinessConstant.OSSTR_YWC)) {
			LOG.error("回访订单失败，订单状态不正确");
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_941);
		}
		// 更新订单
		Order order = new Order();
		Date now = CommonUtils.getNowD();
		order.setOrderCode(orderCode);
		order.setOrderReceiveAmount(new BigDecimal((String) map.get("receiveAmount")));
		order.setOrderDiscountAmount(
				orderDB.getOrderTotalAmount().subtract(new BigDecimal((String) map.get("receiveAmount"))));
		order.setOrderSignStatus(BusinessConstant.OSS_YQS);
		if (osStr.equals(BusinessConstant.OSSTR_DWX)) {
			order.setOrderSignTime(CommonUtils.parseDate3((String) map.get("orderSignTime")));
			order.setOrderSignStatus(BusinessConstant.OSS_YQS);
		}
		order.setOrderFollowStatus(BusinessConstant.OFS_YHF);
		order.setOrderFollowTime(now);
		order.setOrderFollowManagerId(managerId);
		order.setUpdateDate(now);
		order.setUpdateBy(0 - managerId);
		orderDao.updateEntity(order);
		// 插入回访表
		Follow follow = new Follow();
		follow.setOrderId(Integer.parseInt(orderDB.getId()));
		follow.setFollowTime(now);
		follow.setFollowManagerId(managerId);
		follow.setFollowAttitudeScore(new BigDecimal((String) map.get("followAttitudeScore")));
		follow.setFollowQualityScore(new BigDecimal((String) map.get("followQualityScore")));
		follow.setFollowPriceScore(new BigDecimal((String) map.get("followPriceScore")));
		follow.setFollowTotalScore(new BigDecimal((String) map.get("followTotalScore")));
		follow.setFollowRemark((String) map.get("followRemark"));
		follow.setCreateBy(managerId);
		follow.setCreateDate(now);
		follow.setUpdateDate(now);
		follow.setDelFlag(0);
		followDao.saveEntity(follow);
		// 插入操作履历
		saveOrderAction(BusinessConstant.ORDER_ACTION_FOLLOW, 0 - managerId, now, Integer.parseInt(orderDB.getId()),
				orderDB.getOrderStatus(), orderDB.getOrderCheckStatus(), orderDB.getOrderConfirmStatus(),
				orderDB.getOrderPayStatus(), BusinessConstant.OSS_YQS, BusinessConstant.OFS_YHF,
				orderDB.getOrderCommentStatus());
		if (osStr.equals(BusinessConstant.OSSTR_DWX)) {
			// 发送消息模版
			WeixinEntity weixin = weixinDao.getEntity(null, null, null);
			MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
					weixin.getWeixinAppSecret());
			// 通过用户id获取车主openId
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("peopleId", orderDB.getPeopleId());
			WeixinPeopleEntity weixinPeopleC = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
			messageTemplateUtils.sendToUser(weixinPeopleC.getWeixinPeopleOpenId(),
					"tuJeAEDbJCdBBs8IHD2ugm5BvtRF56U9C4BPZGPAT7Y", orderDetailUrlC + orderDB.getOrderCode(), "#000000",
					"您好，您的车辆已完成维修。", "#000000", "请您对本次服务进行评价。", "#000000", order.getOrderCode(), "待评价");
			LOG.info("向openId" + weixinPeopleC.getWeixinPeopleOpenId() + "推送订单状态变更消息成功");
		}
	}

	/**
	 * 
	 * sendAppointmentMessage:推送预约消息通知. <br/>
	 *
	 * @author puyf
	 * @since JDK 1.7
	 */
	public void sendAppointmentMessage() throws Exception {
		// 查询明天到店的订单
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderAppointTime", CommonUtils.getDate(1));
		List<String> osStringList = Arrays.asList(BusinessConstant.OSSTR_DWX);
		paramMap.put("orderStatus", osStringList);
		List<Order> orderList = orderDao.queryOrderList(paramMap);

		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		MessageTemplateUtils messageTemplateUtils = new MessageTemplateUtils(weixin.getWeixinAppID(),
				weixin.getWeixinAppSecret());

		if (orderList != null && orderList.size() != 0) {
			for (Order order : orderList) {
				// 通过用户id获取车主openId
				Map<String, Object> requestMap = new HashMap<String, Object>();
				requestMap.put("peopleId", order.getPeopleId());
				WeixinPeopleEntity weixinPeople = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
				// 通过服务单位id获取服务单位信息
				// paramMap.clear();
				// paramMap.put("id", order.getEnterpriseId());
				// paramMap.put("objectType",
				// BusinessConstant.FILE_TYPE_ENTERPRISE_IMG);
				// Enterprise enterprise =
				// enterpriseDao.queryEnterprise(paramMap);
				// 发送消息模版
				messageTemplateUtils.sendToUser(weixinPeople.getWeixinPeopleOpenId(),
						"47UDm-wi64zmZHy-vt4F6YjQnWGlf0ntQcPP5wlcjF8", orderDetailUrlC + order.getOrderCode(),
						"#000000", "您好，您所预约的维修时间将近！", "#000000", "我们将准时等候您的到来！", "#000000",
						CommonUtils.formatDate3(order.getOrderAppointTime()), order.getOrderGoods(),
						order.getEnterpriseName(), order.getEnterpriseAddress(), order.getEnterpriseTel());
				LOG.info("向openId" + weixinPeople.getWeixinPeopleOpenId() + "推送预约提醒消息成功");
			}
		}
	}

	/**
	 * 
	 * saveOrderAction:插入订单履历表. <br/>
	 *
	 * @author puyf
	 * @param oahActionType
	 * @param oahActionPerpleId
	 * @param oahActionTime
	 * @param orderId
	 * @param orderStatus
	 * @param orderCheckStatus
	 * @param orderConfirmStatus
	 * @param orderPayStatus
	 * @param orderSignStatus
	 * @param orderFollowStatus
	 * @param orderCommentStatus
	 * @param createBy
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void saveOrderAction(String oahActionType, Integer oahActionPerpleId, Date oahActionTime, Integer orderId,
			Byte orderStatus, Byte orderCheckStatus, Byte orderConfirmStatus, Byte orderPayStatus, Byte orderSignStatus,
			Byte orderFollowStatus, Byte orderCommentStatus) throws Exception {
		OrderAction orderAction = new OrderAction();
		orderAction.setOahActionType(oahActionType);
		orderAction.setOahActionPerpleId(oahActionPerpleId);
		orderAction.setOahActionTime(oahActionTime);
		orderAction.setOrderId(orderId);
		orderAction.setOrderStatus(orderStatus);
		orderAction.setOrderCheckStatus(orderCheckStatus);
		orderAction.setOrderConfirmStatus(orderConfirmStatus);
		orderAction.setOrderPayStatus(orderPayStatus);
		orderAction.setOrderSignStatus(orderSignStatus);
		orderAction.setOrderFollowStatus(orderFollowStatus);
		orderAction.setOrderCommentStatus(orderCommentStatus);
		orderAction.setCreateBy(oahActionPerpleId);
		orderAction.setCreateDate(oahActionTime);
		orderAction.setUpdateDate(oahActionTime);
		orderAction.setDelFlag(0);
		orderActionDao.saveEntity(orderAction);
	}

	/**
	 * 
	 * convertOrderStatus:转换状态（1->000000）. <br/>
	 *
	 * @author puyf
	 * @param osIntList
	 * @param isFront
	 * @return
	 * @since JDK 1.7
	 */
	private Set<String> convertOrderStatus(Set<Integer> osIntSet, boolean isFront) {
		// 全部
		if (osIntSet.contains(BusinessConstant.OSINT_ALL)) {
			osIntSet.addAll(statusMap.values());
		}
		if (isFront && osIntSet.contains(BusinessConstant.OSINT_F_DCL)) {
			// 前台请求，待处理为待审核和待确认两个状态
			osIntSet.add(BusinessConstant.OSINT_DSH);
			osIntSet.add(BusinessConstant.OSINT_DQR);
		}
		Set<String> osStringSet = new HashSet<String>();
		for (int osInt : osIntSet) {
			for (Entry<String, Integer> e : statusMap.entrySet()) {
				if (e.getValue() == osInt) {
					osStringSet.add(e.getKey());
				}
			}
		}
		return osStringSet;
	}

	/**
	 * 
	 * convertOrderStatus:转换状态（000000->1）. <br/>
	 *
	 * @author puyf
	 * @param osStr
	 * @return
	 * @since JDK 1.7
	 */
	private int convertOrderStatus(String osStr, boolean isFront) {
		int osInt = -1;
		for (Entry<String, Integer> e : statusMap.entrySet()) {
			if (e.getKey().equals(osStr)) {
				osInt = e.getValue();
				/*
				 * if (isFront) { // 数据库中待审核和待确认俩状态对应前台同一待处理状态 if (osInt ==
				 * BusinessConstant.OSINT_DQR || osInt ==
				 * BusinessConstant.OSINT_DSH) { osInt =
				 * BusinessConstant.OSINT_F_DCL; } }
				 */
				break;
			}
		}
		return osInt;
	}

	/**
	 * 
	 * getOsStr:获取数据库状态组合. <br/>
	 *
	 * @author puyf
	 * @param order
	 * @return
	 * @since JDK 1.7
	 */
	public static String getOsStr(Order order) {
		return "" + order.getOrderStatus() + order.getOrderCheckStatus() + order.getOrderConfirmStatus()
				+ order.getOrderPayStatus() + order.getOrderSignStatus() + order.getOrderCommentStatus();
	}

	/**
	 * 
	 * getWxItems:(根据条件获取配件信息). <br/>
	 *
	 * @author Administrator
	 * @param paramMap
	 * @return
	 * @throws SQLException
	 * @since JDK 1.7
	 */
	public List<Map<String, Object>> getWxItems(Map<String, Object> paramMap) throws SQLException{
		return orderDao.getWxItems(paramMap);
	}
 
}
